package cn.sise.edu.crm.web.controller;

import cn.sise.edu.crm.domain.JsonResult;
import cn.sise.edu.crm.domain.Permission;
import cn.sise.edu.crm.domain.Role;
import cn.sise.edu.crm.query.QueryObject;
import cn.sise.edu.crm.service.IPermissionService;
import cn.sise.edu.crm.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by chen on 2019/11/3.
 */
@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/list")
    @RequiresPermissions(value = {"角色页面", "role:list"},logical = Logical.OR)
    public String list(Model model, @ModelAttribute("qo") QueryObject qo) {
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "role/list";
    }

    @RequestMapping("/input")
    @RequiresPermissions(value = {"角色信息页面", "role:iuput"},logical = Logical.OR)
    public String input(Long id, Model model) {
        List<Permission> permissions = permissionService.selectAll();
        model.addAttribute("permissions", permissions);
        if (id != null) {
            Role role = roleService.selectById(id);
            model.addAttribute("role", role);
            return "/role/input";
        } else {
            return "/role/input";
        }
    }

    @RequestMapping("/delete")
    @ResponseBody
    @RequiresPermissions(value = {"角色删除", "role:delete"},logical = Logical.OR)
    public JsonResult delete(Long id) {
        try {
            roleService.delete(id);
        } catch (Exception e) {
            return new JsonResult("删除失败", false);
        }
        return new JsonResult("删除成功", true);
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    @RequiresPermissions(value = {"角色增加或更新", "role:saveOrUpdate"},logical = Logical.OR)
    public JsonResult saveOrUpdate(Role role, Long[] permissionIds) {
        try {
            if (role.getId() != null) {
                roleService.update(role, permissionIds);
            } else {
                roleService.insert(role, permissionIds);
            }
        } catch (Exception e) {
            return new JsonResult("保存或者更新失败", false);
        }
        return new JsonResult("保存或者更新成功", true);
    }
}
